import Configs from "@/config";
import React from "react";
import SquareGroupViewer from "./SquareGroupViewer";
import { Game } from "@/core/Game";
import { IGameViewer } from "@/core/types";
import { SquareGroup } from "@/core/SquareGroup";
import { SquarePageViewer } from "./SquarePageViewer";

export class GameViewer implements IGameViewer {
  showNext(teris: SquareGroup): void {
    console.log("显示下一个方块", teris);
  }
  switch(teris: SquareGroup): void {
    console.log("切换方块", teris);
  }
  constructor(
    showFn: (teris: SquareGroup) => void,
    switchFn: (teris: SquareGroup) => void
  ) {
    this.showNext = showFn;
    this.switch = switchFn;
  }
}

interface IGameViewerProps {}
const GamePageViewer: React.FC<IGameViewerProps> = () => {
  const [_, forceRender] = React.useState({});
  const [game, setGame] = React.useState<Game | null>(null);
  React.useEffect(() => {
    const g = new Game(
      new GameViewer(
        (teris) => {
          console.log("显示下一个方块", teris);
          teris.squares.forEach((sq) => {
            sq.viewer = new SquarePageViewer(
              (sq) => {
                forceRender({});
              },
              () => {
                console.log("移除小方块");
              }
            );
          });
          // forceRender({});
          // console.log("显示下一个方块", teris);
        },
        (teris) => {
          teris.squares.forEach((sq) => {
            sq.viewer?.remove();
            sq.viewer = new SquarePageViewer(
              (sq) => {
                forceRender({});
              },
              () => {
                console.log("移除小方块");
              }
            );
          });
          console.log("切换方块", teris);
        }
      )
    );
    setGame(g);
    g.start();
  }, []);
  return (
    <div className="flex justify-center  mt-[50px]">
      <div
        className="bg-black relative box-content"
        style={{
          width: `${Configs.panelWidth * Configs.SquareSize}px`,
          height: `${Configs.panelHeight * Configs.SquareSize}px`,
          border: "2px solid #ccc",
        }}
      >
        <SquareGroupViewer group={game?.curTeris} />
      </div>
      <div
        className="relative box-content"
        style={{
          width: `${Configs.nextPanelWidth * Configs.SquareSize}px`,
          height: `${Configs.nextPanelWidth * Configs.SquareSize}px`,
          border: "2px solid #ccc",
        }}
      >
        <SquareGroupViewer group={game?.nextTeris} />
      </div>
    </div>
  );
};

export default GamePageViewer;
